#include "protocol.hpp"
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <stdlib.h>

namespace Cli
{
    class Client
    {
    private:
        int sock;
        uint16_t port;
        std::string ip; 
    public:
        Client(const std::string _ip,uint16_t _port):ip(_ip),port(_port),sock(-1){}
        ~Client()
        {
            if(sock>=0) close(sock);
        }
        void InitClient()
        {
            //1.创建套接字文件
            int sock=socket(AF_INET,SOCK_STREAM,0);
            if(sock<0)
            {
                std::cerr<<"socket"<<std::endl;
                exit(2);
            }
        }

        void Loop()
        {
             //2.填写ip和port
            struct sockaddr_in ser_peer;
            socklen_t len=sizeof(ser_peer);
            bzero(&ser_peer,len);
            ser_peer.sin_family=AF_INET;
            ser_peer.sin_port=htons(port);
            ser_peer.sin_addr.s_addr=inet_addr(ip.c_str());
            //3.发起链接
            if(connect(sock,(struct sockaddr*)&ser_peer,len) < 0)
            {
                std::cerr<<"connect"<<std::endl;
                exit(3);
            }
            //4.收发数据
            while(true)
            {
                ns_protocol::Request req;
                std::cout<<"请输入第一个数据#";
                std::cin>>req.x;
                std::cout<<"请输入第二个数据#";
                std::cin>>req.y;
                std::cout<<"请输入运算符#";
                std::cin>>req.op;

                send(sock,&req,sizeof(req),0);
                ns_protocol::Response resp;
                ssize_t s=recv(sock,&resp,sizeof(resp),0);
                if(s > 0)
                {
                    std::cout<<"code#"<<resp.code<<std::endl;
                    std::cout<<"result#"<<resp.result<<std::endl;
                }

            }
        }
    };
}